package com.fenghongzhang.day014;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MyIntentService extends IntentService {

    private static final String TAG = "MyIntentService";
    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }

    /**
     * 在子线程中执行,
     * 执行完毕以后,服务自动停止.
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {

        Log.i(TAG, "onHandleIntent: ");
        StringBuffer sb=new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;
        try {
            URL url=new URL("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
            connection = (HttpURLConnection) url.openConnection();
//            connection.setReadTimeout(5*1000);
//            connection.setConnectTimeout(5*1000);

            if(connection.getResponseCode()==200){
                inputStream  = connection.getInputStream();
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
                Log.i(TAG, "onHandleIntent: "+sb.toString());
               //使用广播的方式发送
                Intent intent1=new Intent();
                intent1.setAction("com.bawei.intentservice");
                Bundle bundle = new Bundle();
                bundle.putString("json",sb.toString());
                intent1.putExtras(bundle);
                sendBroadcast(intent1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                connection.disconnect();
            }
        }

    }

}
